<?php
//$Id: app.php 460 2012-07-09 08:27:03Z tomqin@gmail.com $

/**
 * 支付宝接口插件
 *
 * @copyright       Copyright (C) 2010-2012 Ling-Rui Tech. Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         htt://www.supefun.com/license/
 * @package Core.Payment
 */


class Alipay {
    private $key         = '';
    private $partner     = '';
    private $account     = '';
    private $notify_url  = '';
    private $return_url  = '';
    private $charset     = 'utf-8';
    private $gateway     = 'https://mapi.alipay.com/gateway.do';

    static private $unionBanks = array (
        //'directPay' => array('支付宝',          'alipay.gif'),
        'ICBCB2C'   => array('中国工商银行',    'logo_120.jpg'),
        'CMB'       => array('招商银行',        'logo_013.jpg'),
        'BOCB2C'    => array('中国银行',        'logo_134.jpg'),
        'CCB'       => array('中国建设银行',    'logo_005.jpg'),
        'ABC'       => array('中国农业银行',    'logo_008.jpg'),
        'COMM'      => array('交通银行',        'logo_006.jpg'),
        'CEBBANK'   => array('中国光大银行',    'logo_133.jpg'),
        'GDB'       => array('广东发展银行',    'logo_002.jpg'),
        'CMBC'      => array('中国民生银行',    'logo_007.jpg'),
        'CITIC'     => array('中信银行',        'logo_016.jpg'),
        'CIB'       => array('兴业银行',        'logo_011.jpg'),
        'POSTGC'    => array('中国邮政储蓄银行','logo_139.jpg'),
    );

    static function getUnionBanks(){
        return self::$unionBanks;
    }

    static function getConfig(){
        return array(
            'partner'    => '2088801104976420',
            'key'        => 'dgiybd7wcallwjq7weu8catl0anud6sl',
            'account'    => 'sudingke@163.com',
            'notify_url' => 'http://kusotuan.com/payment/notify.php',
            'return_url' => 'http://dl.sudingke.xxx/order/alipay/return',
        );
    }

    function __construct($config) {
        $this->key = isset($config['key']) ? $config['key'] : '';
        $this->partner = isset($config['partner']) ? $config['partner'] : '';
        $this->account = isset($config['account']) ? $config['account'] : '';
        $this->notify_url = isset($config['notify_url']) ? $config['notify_url'] : '';
        $this->return_url = isset($config['return_url']) ? $config['return_url'] : '';
        $this->charset = 'utf-8';
        $this->gateway = 'https://mapi.alipay.com/gateway.do';
    }

    /**
     * 生成支付代码
     * @param   array   $order      订单信息
     * @param   bool    $isform     是否使用表单模式(推荐)
     * @param   array   $payment    支付方式信息
     */
    function getPaymentCode($order, $isform = true) {
        $real_method = intval($order['pay_method']);
        switch ($real_method){
            case '2':
                $service = 'create_direct_pay_by_user';
                break;
            case '1':
                $service = 'create_partner_trade_by_buyer';
                break;
            case '0':
            default:
                $service = 'trade_create_by_buyer';
                break;
        }

        $paymethod    = '';
        $defaultbank  = '';

        if (isset(self::$unionBanks[$order['pay_bank']])){
            $paymethod = 'bankPay';
            $defaultbank = $order['pay_bank'];
            $bankname   = self::$unionBanks[$order['pay_bank']][0];
            $bankimage  = self::$unionBanks[$order['pay_bank']][1];
        } else {
            $paymethod = 'directPay';
            $bankname  = '支付宝';
            $bankimage = 'alipay.gif';
        }

        $parameter = array(
            //'extend_param'      => $extend_param,
            'service'           => $service,
            'partner'           => $this->partner,
            '_input_charset'    => $this->charset,
            'notify_url'        => $this->notify_url,
            'return_url'        => $this->return_url,
            /* 业务参数 */
            'subject'           => iconv_substr($order['order_title'], 0, 128, $this->charset),    //商品的标题/ 交易标题/ 订单标题/ 订单关键字等。
                                                                                             //该参数最长为128 个汉字。
            'body'              => $order['order_desc'],                                     //商品描述 String(400),可空
            'out_trade_no'      => $order['order_code'],
            'price'             => $order['order_amount'],
            'quantity'          => 1,
            'payment_type'      => 1,

            'paymethod'         => $paymethod,
            'defaultbank'       => $defaultbank,

            /* 物流参数 */
            'logistics_type'    => 'EXPRESS',
            'logistics_fee'     => 0,
            'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',

            /* 买卖双方信息 */
            'seller_email'      => $this->account,
        );

        if($isform){
            $button    = $this->buildForm($parameter, 'post', '立即用'.$bankname.'支付');
        }else{
            $alipayurl = $this->buildGetway($parameter);
            $button    = '<input id="alipaysubmit" type="button" onclick="window.open(\''.$alipayurl.'\')" value="立即用'.$bankname.'支付" />';
        }

        $button = '<div style="width:150px;border:1px #ccc solid;margin:10px auto;text-align:center;padding:10px 20px;">'
                 .'<img src="'.STATIC_URL.'img/common/checkout/'.$bankimage.'" align="absmiddle" alt="'.$bankname.'"  /></div>'
                 .$button;

        return $button;
    }

    function buildGetway(array $parameter){
        ksort($parameter);
        reset($parameter);

        $param = $sign = '';
        foreach ($parameter as $key => $val) {
            if(!empty($val)){
                $param .= "$key=" .urlencode($val). "&";
                $sign  .= "$key=$val&";
            }
        }

        $param = substr($param, 0, -1);
        $sign  = substr($sign, 0, -1). $this->key;

        return $this->gateway.'?'.$param. '&sign='.md5($sign).'&sign_type=MD5';
    }

    /**
     * 构造提交表单HTML数据
     * @param $para_temp 请求参数数组
     * @param $gateway 网关地址
     * @param $method 提交方式。两个值可选：post、get
     * @param $button_name 确认按钮显示文字
     * @return 提交表单HTML文本
     */
    function buildForm(array $parameter, $method = 'post', $button = '立即支付') {
        $method = (strtoupper($method) == 'GET') ? 'GET' : 'POST';

        ksort($parameter);
        reset($parameter);

        $html  = '<form id="alipayform" name="alipayform" action="'.$this->gateway.'?_input_charset='.trim($this->charset).'" method="'.$method.'">';
        $sign  = '';
        foreach ($parameter as $key => $val) {
            if(!empty($val)){
                $html  .= '<input type="hidden" name="'.$key.'" value="'.h($val).'"/>';
                $sign  .= "$key=$val&";
            }
        }
        $sign   = substr($sign, 0, -1). $this->key;

        $html  .= '<input type="hidden" name="sign_type" value="MD5" />';
        $html  .= '<input type="hidden" name="sign" value="'.md5($sign).'" />';
        $html  .= '<input type="submit" name="" id="alipaysubmit" value="'.$button.'" class="btns" />';
        $html  .= '</form>';

        return $html;
    }

    function checkSign(array $params){
        /* 检查数字签名是否正确 */
        ksort($params);
        reset($params);

        $sign = '';
        foreach ($params AS $key=>$val){
            if ($key != 'sign' && $key != 'sign_type' && $key != 'code'){
                $sign .= "$key=$val&";
            }
        }

        $sign = substr($sign, 0, -1) . $this->key;
        if (md5($sign) != $params['sign']) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 响应操作
     */
    function respond()
    {
        if (!empty($_POST))
        {
            foreach($_POST as $key => $data)
            {
                $_GET[$key] = $data;
            }
        }
        $payment  = get_payment($_GET['code']);
        $seller_email = rawurldecode($_GET['seller_email']);
        $order_sn = str_replace($_GET['subject'], '', $_GET['out_trade_no']);
        $order_sn = trim($order_sn);

        /* 检查支付的金额是否相符 */
        if (!check_money($order_sn, $_GET['total_fee']))
        {
            return false;
        }

        /* 检查数字签名是否正确 */
        ksort($_GET);
        reset($_GET);

        $sign = '';
        foreach ($_GET AS $key=>$val)
        {
            if ($key != 'sign' && $key != 'sign_type' && $key != 'code')
            {
                $sign .= "$key=$val&";
            }
        }

        $sign = substr($sign, 0, -1) . $payment['alipay_key'];
        //$sign = substr($sign, 0, -1) . ALIPAY_AUTH;
        if (md5($sign) != $_GET['sign'])
        {
            return false;
        }

        if ($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS')
        {
            /* 改变订单状态 */
            order_paid($order_sn, 2);

            return true;
        }
        elseif ($_GET['trade_status'] == 'TRADE_FINISHED')
        {
            /* 改变订单状态 */
            order_paid($order_sn);

            return true;
        }
        elseif ($_GET['trade_status'] == 'TRADE_SUCCESS')
        {
            /* 改变订单状态 */
            order_paid($order_sn, 2);

            return true;
        }
        else
        {
            return false;
        }
    }
}


class AlipayService{

    //static function

}
?>